package com.cpfmat.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.cpfmat.common.CommonStringUtils;
import com.cpfmat.common.Contains;
import com.cpfmat.entity.Article;
import com.cpfmat.entity.Attachment;
import com.cpfmat.entity.SystemMenu;
import com.cpfmat.service.IArticleService;
import com.cpfmat.service.IAttachmentService;
import com.cpfmat.vo.CustomArticle;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zhangbin
 * @since 2018-07-30
 */
@Controller
public class ArticleController {

	@Autowired
	private IArticleService articleService;
	@Autowired
	private IAttachmentService attachmentService;

	/**
	 * 初始化JSP页面 直接返回到JSP页面中
	 * 
	 * @return
	 */
	@RequestMapping(path = "/manage/article/init/{type}")
	public ModelAndView init(@PathVariable("type") String type) {
		ModelAndView view = new ModelAndView("/manage/article/list");
		view.addObject("type",type);
		return view;
	}

	/**
	 * 通过查询参数以及分页获取列表 返回ajaxtr.jsp页面 展示数据
	 * 
	 * @param pageNum
	 * @param weekPlanName
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(path = "/manage/article/column/{columnName}")
	public ModelAndView column(@RequestParam(defaultValue = "1", name = "pageNum") int pageNum,
			@RequestParam(required = false, name = "title") String title,
			@PathVariable("columnName") String columnName) throws Exception {
		ModelAndView view = new ModelAndView("/manage/article/ajaxtr");
		
		String columnId = null,parentColumnId = null;
		switch (columnName) {
		case "index":
			columnId = Contains.menuKeyMap.get(columnName).getSeqId();
			break;
		case "news":
			columnId = Contains.menuKeyMap.get(columnName).getSeqId();
			break;
		case "platform":
			columnId = Contains.menuKeyMap.get(columnName).getSeqId();
			break;
		case "about":
			columnId = Contains.menuKeyMap.get(columnName).getSeqId();
			break;
		case "authority":
			columnId = Contains.menuKeyMap.get(columnName).getSeqId();
			break;
		default:
			throw new Exception("找不到" + columnName + "对应的菜单信息");
		}

		Page<CustomArticle> page = this.queryList(pageNum, Contains.PAGE_SIZE, title, parentColumnId,columnId);
		view.addObject("page",page);
		view.addObject("type",columnName);
		return view;
	}
	
	/**
	 * 通过查询参数以及分页获取列表 返回ajaxtr.jsp页面 展示数据
	 * 
	 * @param pageNum
	 * @param weekPlanName
	 * @return
	 */
	@RequestMapping(path = "/manage/article/list")
	public ModelAndView list(@RequestParam(defaultValue = "1", name = "pageNum") int pageNum,
			@RequestParam(required = false, name = "title") String title,
			@RequestParam(required = false, name = "columnId") String columnId) {
		ModelAndView view = new ModelAndView("/manage/article/ajaxtr");

		Page<CustomArticle> page = this.queryList(pageNum, Contains.PAGE_SIZE, title, null, columnId);
		view.addObject("page",page);
		view.addObject("type","list");
		return view;
	}

	/**
	 * 根据主键ID新增文章
	 * @param seqId
	 * @return
	 */
	@RequestMapping(path = "/manage/article/insert")
	public @ResponseBody String insert(@RequestParam(required = true, name = "title") String title,
			@RequestParam(required = false, name = "subTitle") String subTitle,
			@RequestParam(required = true, name = "columnId") String columnId,
			@RequestParam(required = false, name = "industry") String industry,
			@RequestParam(required = false, name = "subIndustry") String subIndustry,
			@RequestParam(required = true, name = "content") String content,
			@RequestParam(required = false, name = "imagePath") String imagePath,
			@RequestParam(required = false, name = "provider") String provider,
			@RequestParam(required = false, name = "description") String description,
			@RequestParam(required = false, name = "insertUser") String insertUser,
			@RequestParam(required = false, name = "insertTime") String insertTime,
			@RequestParam(required = false, name = "isShow") int isShow,
			@RequestParam(required = false, name = "attachmentId") String[] attachments) {

		Article article = new Article();
		Date nowTime = new Date();
		String articleSeqId = CommonStringUtils.getUUID();

		article.setDelFlag(0);
		article.setContent(content);
		article.setSeqId(articleSeqId);
		article.setColumnId(columnId);
		article.setImagePath(imagePath);
		article.setIndustry(industry);
		article.setInsertUser(insertUser);
		article.setSubIndustry(subIndustry);
		article.setTitle(title);
		article.setDescription(description);
		article.setSubTitle(subTitle);
		article.setUpdateCounts(0);
		article.setUpdateTime(nowTime);
		article.setProvider(provider);
		article.setViewCounts(0);
		article.setIsShow(isShow);
		
		try{
			if(StringUtils.isNotBlank(insertTime)){
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				Date insertTimeDB = sdf.parse(insertTime);
				article.setInsertTime(insertTimeDB);
			}
		} catch(Exception e){
			e.printStackTrace();
		}
		
		String validateObj = validate(article);

		if ("success".equals(validateObj)) {
			try {
				articleService.insert(article);
			} catch (Exception e) {
				validateObj = "DM_ER";
				e.printStackTrace();
			}

			// 更新附件的所属主键ID
			if (attachments != null && attachments.length > 0) {
				StringBuilder sb = new StringBuilder();
				int length = attachments.length;
				for(String attachmentId : attachments){
					sb.append(attachmentId);
					if(--length > 0){
						sb.append(",");
					}
				}
				String attachmentIds = sb.toString();
				EntityWrapper<Attachment> wrapper = new EntityWrapper<Attachment>();
				wrapper.in("SEQ_ID", attachmentIds);
				wrapper.eq("DEL_FLAG", 0);
				
				List<Attachment> selectList = attachmentService.selectList(wrapper);
				Iterator<Attachment> iterator = selectList.iterator();
				while(iterator.hasNext()){
					Attachment attachment = iterator.next();
					attachment.setArticleId(articleSeqId);
				}
				attachmentService.updateBatchById(selectList, Contains.BATCH_COUNTS);
			}
		}

		return validateObj;
	}

	/**
	 * 根据主键ID删除及其未读记录
	 * 
	 * @param seqId
	 * @return
	 */
	@RequestMapping(path = "/manage/article/modify")
	public @ResponseBody String modify(@RequestParam(required = true, name = "seqId") String seqId,
			@RequestParam(required = true, name = "title") String title,
			@RequestParam(required = false, name = "subTitle") String subTitle,
			@RequestParam(required = true, name = "columnId") String columnId,
			@RequestParam(required = false, name = "industry") String industry,
			@RequestParam(required = false, name = "subIndustry") String subIndustry,
			@RequestParam(required = true, name = "content") String content,
			@RequestParam(required = false, name = "imagePath") String imagePath,
			@RequestParam(required = false, name = "provider") String provider,
			@RequestParam(required = false, name = "insertUser") String insertUser,
			@RequestParam(required = false, name = "insertTime") String insertTime,
			@RequestParam(required = false, name = "description") String description,
			@RequestParam(required = false, name = "isShow") int isShow,
			@RequestParam(required = false, name = "attachmentId") String[] attachments) {

		Article article = new Article();
		Date nowTime = new Date();

		article.setDelFlag(0);
		article.setContent(content);
		article.setSeqId(seqId);
		article.setColumnId(columnId);
		article.setImagePath(imagePath);
		article.setIndustry(industry);
		article.setInsertUser(provider);
		article.setSubIndustry(subIndustry);
		article.setTitle(title);
		article.setSubTitle(subTitle);
		article.setDescription(description);
		article.setUpdateTime(nowTime);
		article.setInsertUser(insertUser);
		article.setProvider(provider);
		article.setIsShow(isShow);
		
		try{
			if(StringUtils.isNotBlank(insertTime)){
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				Date insertTimeDB = sdf.parse(insertTime);
				article.setInsertTime(insertTimeDB);
			}
		} catch(Exception e){
			e.printStackTrace();
		}

		String validateObj = validate(article);

		if ("success".equals(validateObj)) {

			try {
				articleService.customUpdate(article);
			} catch (Exception e) {
				validateObj = "DM_ER";
				e.printStackTrace();
			}

			// 更新附件的所属主键ID
			if (attachments != null && attachments.length > 0) {
				StringBuilder sb = new StringBuilder();
				int length = attachments.length;
				for(String attachmentId : attachments){
					sb.append(attachmentId);
					if(--length > 0){
						sb.append(",");
					}
				}
				String attachmentIds = sb.toString();
				EntityWrapper<Attachment> wrapper = new EntityWrapper<Attachment>();
				wrapper.in("SEQ_ID", attachmentIds);
				wrapper.isNull("ARTICLE_ID");
				wrapper.eq("DEL_FLAG", 0);
				
				List<Attachment> selectList = attachmentService.selectList(wrapper);
				if(selectList != null && selectList.size() > 0){
					Iterator<Attachment> iterator = selectList.iterator();
					while(iterator.hasNext()){
						Attachment attachment = iterator.next();
						attachment.setArticleId(seqId);
					}
					
					attachmentService.updateBatchById(selectList, Contains.BATCH_COUNTS);
				}
			}
		}
		return validateObj;
	}

	/**
	 * 根据主键ID查看详情
	 * 
	 * @param seqId
	 * @return
	 */
	@RequestMapping(path = "/manage/article/preview")
	public ModelAndView preview(@RequestParam(required = false, name = "seqId") String seqId) {
		ModelAndView view = new ModelAndView("/manage/article/preview");

		if (StringUtils.isNotBlank(seqId)) {
			CustomArticle article = articleService.detailWithAttachments(seqId);

			view.addObject("article", article);
		}

		return view;
	}
	
	/**
	 * 根据主键ID查看详情 用于创建新增及修改列表
	 * 
	 * @param seqId
	 * @return
	 */
	@RequestMapping(path = "/article/detail/{seqId}")
	public ModelAndView detail(@PathVariable("seqId") String seqId,@RequestParam(required = false, name = "type") String type) {
		ModelAndView view = new ModelAndView("/new/listDetail");

		CustomArticle article = articleService.detailWithAttachments(seqId);
		
		if(article != null){
			Article updateArticle = new Article();
			updateArticle.setSeqId(article.getSeqId());
			updateArticle.setViewCounts(article.getViewCounts() + 1);
			updateArticle.setInsertTime(article.getInsertTime());
			articleService.updateById(updateArticle);
		}

		view.addObject("article", article);
		view.addObject("type", type);

		return view;
	}

	/**
	 * 根据主键ID查看详情 用于创建新增及修改列表
	 * 
	 * @param seqId
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(path = "/manage/article/edit")
	public ModelAndView edit(String seqId,@RequestParam(required = false,name = "type") String type) throws Exception {
		ModelAndView view = new ModelAndView("/manage/article/detail");

		CustomArticle article = articleService.detailWithAttachments(seqId);

		view.addObject("article", article);
		List<SystemMenu> menuInfo = new ArrayList<SystemMenu>();
		
		if(StringUtils.isNotBlank(type)){
			if(Contains.menuKeyMap.get(type) != null){
				menuInfo.add(Contains.menuKeyMap.get(type));
			}
		}
		else{
			throw new Exception("找不到" + type + "对应的菜单信息");
		}
		
		view.addObject("columns", menuInfo);

		return view;
	}

	/**
	 * 根据主键ID删除及其未读记录
	 * 
	 * @param seqId
	 * @return
	 */
	@RequestMapping(path = "/manage/article/del")
	@ResponseBody
	public boolean del(String seqId) {
		try{
			Article article = new Article();
	
			article.setSeqId(seqId);
			article.setDelFlag(1);
	
			articleService.updateById(article);
			return true;
		} catch(Exception e){
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * @param attachmentId
	 * @return
	 */
	@RequestMapping("/manage/article/delAttachment")
	@ResponseBody
	public boolean delAttachment(String attachmentId) {
		try {
			Attachment attachment = new Attachment();
			
			attachment.setSeqId(attachmentId);
			attachment.setDelFlag(1);
	
			attachmentService.updateById(attachment);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	private Page<CustomArticle> queryList(int pageNum, int pageSize,String title,String parentColumnId,String columnId) {
		return articleService.getManagePage(title, columnId, parentColumnId,pageNum, pageSize);
	}

	/**
	 * @param obj
	 * @return
	 */
	private String validate(Article obj) {
		String result = "success";
		if (StringUtils.isBlank(obj.getContent())) {
			result = "AC_CN";
		}
		if (StringUtils.isBlank(obj.getColumnId())) {
			result = "AC_IN";
		}
		if (StringUtils.isBlank(obj.getSeqId())) {
			result = "ID_NP";
		}
		if (StringUtils.isBlank(obj.getTitle())) {
			result = "AT_NP";
		}
		return result;
	}

}
